package com.gtc.zsk.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.gtc.zsk.annotation.AuthCheck;
import com.gtc.zsk.common.BaseResponse;
import com.gtc.zsk.common.ErrorCode;
import com.gtc.zsk.common.ResultUtils;
import com.gtc.zsk.config.PayConfig;
import com.gtc.zsk.constant.CommonConstant;
import com.gtc.zsk.constant.UserConstant;
import com.gtc.zsk.exception.ThrowUtils;
import com.gtc.zsk.model.dto.bankMall.NotifyRequest;
import com.gtc.zsk.model.dto.bankMall.SendPaymentRequest;
import com.gtc.zsk.model.dto.questionBank.QuestionBankAddRequest;
import com.gtc.zsk.model.dto.vipBankUser.VipBankUserAddRequest;
import com.gtc.zsk.model.entity.QuestionBank;
import com.gtc.zsk.model.entity.User;
import com.gtc.zsk.model.entity.VipBankUser;
import com.gtc.zsk.model.vo.BankMallBankVO;
import com.gtc.zsk.model.vo.BankMallUserVO;
import com.gtc.zsk.model.vo.BankMallVO;
import com.gtc.zsk.model.vo.PayVO;
import com.gtc.zsk.service.QuestionBankService;
import com.gtc.zsk.service.UserService;
import com.gtc.zsk.service.VipBankUserService;
import com.gtc.zsk.utils.MD5Util;
import com.gtc.zsk.utils.PayUtil;
import com.gtc.zsk.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("/bankMall")
@Slf4j
public class BankMallController {

    @Resource
    private VipBankUserService vipBankUserService;

    @Resource
    private QuestionBankService questionBankService;

    @Resource
    private UserService userService;


    @GetMapping("/info")
    public BaseResponse<BankMallVO> getBankMallInfo(HttpServletRequest request) {
        User currentLoginUser = userService.getLoginUser(request);
        long current = 1;
        long size = 200;
        QueryWrapper<QuestionBank> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("money", 0);
        queryWrapper.orderBy(SqlUtils.validSortField("createTime"),
                false,
                "createTime");
        // 查询数据库
        Page<QuestionBank> questionBankPage = questionBankService.page(new Page<>(current, size), queryWrapper);
        Page<BankMallBankVO> bankMallBankVOPage = questionBankService.getBankMallBankVOPage(questionBankPage, currentLoginUser.getId());
        BankMallUserVO currentLoginBankMallUserVO = BankMallUserVO.objToVo(currentLoginUser);
        BankMallVO bankMallVO = new BankMallVO();
        bankMallVO.setCurrentLoginUser(currentLoginBankMallUserVO);
        bankMallVO.setBankMallBankVOPage(bankMallBankVOPage);
        return ResultUtils.success(bankMallVO);
    }

    @PostMapping("/get/pay")
    public BaseResponse<PayVO> getPayOrder(@RequestBody SendPaymentRequest sendPaymentRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        // 拼接商家订单号
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timeStr = now.format(formatter);
        final String out_trade_no = timeStr + loginUser.getId();
        // 接收前端发来的请求参数
        Long questionBankId = sendPaymentRequest.getQuestionBankId();
        String questionBankTitle = sendPaymentRequest.getQuestionBankTitle();
        Float money = sendPaymentRequest.getMoney();
        String payType = sendPaymentRequest.getPayType();
        ThrowUtils.throwIf(questionBankId == null || questionBankTitle == null || money == null || money < 0 || payType == null, ErrorCode.PARAMS_ERROR, "参数不合法！");
        // 处理参数
        String name = "开通“" + questionBankTitle + "”知识库VIP浏览权限";
        VipBankUserAddRequest vipBankUser = new VipBankUserAddRequest();
        vipBankUser.setQuestionBankId(questionBankId);
        vipBankUser.setUserId(loginUser.getId());
        String param = new Gson().toJson(vipBankUser);
        PayVO payVO = new PayUtil().sendPayment(out_trade_no, name, money, param, payType, questionBankId);
        return ResultUtils.success(payVO);
    }

    @GetMapping("/notify")
    public String notifyZhifu(NotifyRequest notifyRequest){
        if (notifyRequest == null)
            return "fail";
//        Integer pid = notifyRequest.getPid();
//        String out_trade_no = notifyRequest.getOut_trade_no();
//        String type = notifyRequest.getType();
//        String name = notifyRequest.getName();
//        String money = notifyRequest.getMoney();
        String trade_status = notifyRequest.getTrade_status();
        String param = notifyRequest.getParam();
        param = param.replaceAll("&quot;", "\"");
        param = param.replace("\\", "");
        //String sign = notifyRequest.getSign();
        Gson gson = new Gson();
        VipBankUserAddRequest vipBankUserAddRequest = null;
        //Long questionBankId = null;
        try {
            vipBankUserAddRequest = gson.fromJson(param, VipBankUserAddRequest.class);
            //questionBankId = vipBankUserAddRequest.getQuestionBankId();
        } catch (Exception e) {
            System.out.println("出现类型转换异常！");
            return "fail";
        }
//        String mdString = "clientip=" + PayConfig.clientip + "&device=" + PayConfig.device + "&money=" + money + "&name=" + name + "&" +
//                "notify_url=" + PayConfig.notify_url + "&out_trade_no=" + out_trade_no + "&param=" + param + "&pid=" + pid + "&return_url=" + PayConfig.return_url + questionBankId +
//                "&type=" + type + PayConfig.key;
//        //请求参数md5加密后得到签名
//        String genSign = MD5Util.GetMD5Code(mdString);
//        ThrowUtils.throwIf(!genSign.equals(sign), ErrorCode.PARAMS_ERROR, "签名校验失败！！！");
        ThrowUtils.throwIf(!trade_status.equals("TRADE_SUCCESS"), ErrorCode.OPERATION_ERROR, "未成功支付！！！");
        // 走到这说明签名校验成功（说明notifyRequest中各个参数都是对的 都有值） + 支付成功
        // 就可以添加 用户 - 题库vip 关联了
        VipBankUser vipBankUser = new VipBankUser();
        BeanUtils.copyProperties(vipBankUserAddRequest, vipBankUser);
        vipBankUserService.validAndAddVipBankUser(vipBankUser, true);
        return "success";
    }
}
